package com.itouch.bracelet.activity;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONObject;

import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.fourmob.datetimepicker.date.DatePickerDialog.OnDateSetListener;
import com.google.gson.Gson;
import com.itouch.bracelet.R;
import com.itouch.bracelet.bean.BaseResult;
import com.itouch.bracelet.bean.LoginUser;
import com.itouch.bracelet.cache.UserCache;
import com.itouch.bracelet.diseaseinfo.Constants;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;
import com.sleepbot.datetimepicker.time.TimePickerDialog.OnTimeSetListener;

public class AddMedicationActivity extends BaseActivity implements
		OnClickListener, OnDateSetListener,
		OnTimeSetListener {
	public static final String DATEPICKER_TAG = "datepicker";
	public static final String TIMEPICKER_TAG = "timepicker";
	
	public static final int START_CLICK = 1;
	public static final int END_CLICK = 2;
	
	
	
	private int startTemp = -1;
	
	
	
	private LinearLayout content;
	private TextView startTimeText;
	private ImageView startTimeImg;
	private TextView endTimeText;
	private ImageView endTimeImg;
	private LinearLayout addLayout;
	private EditText medName;
	private EditText medNumber;
	private HashMap<Long, View> map = new HashMap<Long, View>();
//	private LayoutParams parentParams;
//	private LayoutParams childParams;
//	private LayoutParams rightParams;
	private LayoutInflater inflater;
	private DatePickerDialog startDatePickerDialog;
	private DatePickerDialog endDatePickerDialog;
	private TimePickerDialog startTimePickerDialog;
	private TimePickerDialog endTimePickerDialog;
	private int type;
	private TextView saveMed;
	private boolean isMother;
	@Override
	protected int setContentViewById() {
		return R.layout.activity_medication_add;
	}

	@Override
	protected void initViews() {
		inflater = LayoutInflater.from(context);
		
		type = getIntent().getIntExtra("type", -1);
		isMother =  0== type ? true : false;
		final Calendar calendar = Calendar.getInstance();
		startDatePickerDialog = DatePickerDialog.newInstance(this,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), false);

		endDatePickerDialog = DatePickerDialog.newInstance(this,
				calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), false);

		startTimePickerDialog = TimePickerDialog.newInstance(this,
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE), false, false);
		endTimePickerDialog = TimePickerDialog.newInstance(this,
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE), false, false);

		content = (LinearLayout) findViewById(R.id.content);
		startTimeText = (TextView) findViewById(R.id.start_time_text);

		saveMed = (TextView) findViewById(R.id.save_med);
		startTimeImg = (ImageView) findViewById(R.id.start_time_img);
		endTimeText = (TextView) findViewById(R.id.end_time_text);
		endTimeImg = (ImageView) findViewById(R.id.end_time_img);
		addLayout = (LinearLayout) findViewById(R.id.add_layout);
		medName = (EditText) findViewById(R.id.med_name);
		medNumber = (EditText) findViewById(R.id.med_number);

		content.setOnClickListener(this);
		addLayout.setOnClickListener(this);
		startTimeImg.setOnClickListener(this);
		endTimeImg.setOnClickListener(this);
		saveMed.setOnClickListener(this);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.save_med:
		if (type == -1) {
			return;
		}
		LoginUser user = UserCache.getOauth(context);
		String customerId="";
		if(isMother){
			customerId=user.getUserId();
		}else{
			//用小孩的id  暂时不处理
			customerId=user.getChildlist().get(user.childPosition).getId();
		}
		
		String startTime= startTimeText.getText().toString();
		if(startTime==null||startTime.length()!=16){
			Toast.makeText(context, R.string.enter_right_starttime, Toast.LENGTH_SHORT).show();
			return;
		}
		
		String endTime= endTimeText.getText().toString();
		if(endTime==null||endTime.length()!=16){
			Toast.makeText(context, R.string.enter_right_endtime, Toast.LENGTH_SHORT).show();
			return;
		}
		
		String medNameString=medName.getText().toString();
		if(medNameString==null||medNameString.length()<1){
			Toast.makeText(context, R.string.enter_right_medname, Toast.LENGTH_SHORT).show();
			return;
		}
		StringBuffer nameBuffer = new StringBuffer();
		nameBuffer.append(medNameString+",");
		
		String medNumString=medNumber.getText().toString();
		if(medNumString==null||medNumString.length()<1){
			Toast.makeText(context, R.string.enter_right_mednumber, Toast.LENGTH_SHORT).show();
			return;
		}
		StringBuffer numberBuffer = new StringBuffer();
		numberBuffer.append(medNumString+",");
		
		boolean isOK = false;
		if(map.size()>0){
			for (Long key : map.keySet()) {
				View  view=   map.get(key);
				EditText  name=(EditText) view.findViewById(R.id.med_name);		
				String  nameString=name.getText().toString();
				if(nameString==null||nameString.length()<1){
					Toast.makeText(context, R.string.enter_right_medname, Toast.LENGTH_SHORT).show();
					return;
				}
				nameBuffer.append(nameString+",");
				
				EditText  number=(EditText) view.findViewById(R.id.med_number);		
				String  numberString=name.getText().toString();
				if(numberString==null||numberString.length()<1){
					Toast.makeText(context, R.string.enter_right_mednumber, Toast.LENGTH_SHORT).show();
					return;
				}
				numberBuffer.append(numberString+",");
			}

		}
		
		nameBuffer.deleteCharAt(nameBuffer.length()-1);
		numberBuffer.deleteCharAt(numberBuffer.length()-1);
		
	   addMedication(nameBuffer.toString(),numberBuffer.toString(),startTime,endTime,customerId);
	
		break;
		case R.id.start_time_img:
			startDatePickerDialog.setVibrate(true);
			startDatePickerDialog.setYearRange(1985, 2028);
			startDatePickerDialog.setCloseOnSingleTapDay(true);
			startDatePickerDialog.show(getSupportFragmentManager(),
					DATEPICKER_TAG);
			startTemp = START_CLICK ;
			break;
		case R.id.end_time_img:
			endDatePickerDialog.setVibrate(true);
			endDatePickerDialog.setYearRange(1985, 2028);
			endDatePickerDialog.setCloseOnSingleTapDay(true);
			endDatePickerDialog.show(getSupportFragmentManager(),
					DATEPICKER_TAG);
			startTemp = END_CLICK ;
			break;

		case R.id.content:

			break;
		case R.id.add_layout:

			final View view = inflater.inflate(R.layout.add_content, null);

			Long time = System.currentTimeMillis();

			view.setTag(time);
			map.put(time, view);

			ImageView delete = (ImageView) view.findViewById(R.id.delete);
			delete.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					
					long position = (Long) view.getTag();
					View view = map.get(position);
					content.removeView(view);
					map.remove(position);

				}
			});

			content.addView(view);
			break;

		default:
			break;
		}

	}

	/**
	 *   添加 
	 */
	private void addMedication(String medicationName,String medicationNum,String medicationDate,String nextMedDate , String  customerId) {
		
		Uri.Builder builder = Uri.parse(Constants.SAVE_MEDICATION).buildUpon();
		//medcationName=11,22,33&medicationNum=4,5,6&medicationDate=2015-02-06&nextMedDate=2015-02-07&customerId=85&creator=254
		builder.appendQueryParameter("medicationName", medicationName);
		builder.appendQueryParameter("medicationNum", medicationNum + "");
		builder.appendQueryParameter("medicationDate", medicationDate + "");
		builder.appendQueryParameter("nextMedDate", nextMedDate + "");
		
		
		builder.appendQueryParameter("customerId", customerId + "");
		builder.appendQueryParameter("creator", "254");

		Log.d("SAVE_MEDICATION", "SAVE_MEDICATION" + builder.toString());

		show();
		getJSONByVolleyGET(builder.toString(),
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject arg0) {
						disMiss();
						Log.d("SAVE_MEDICATION",
								"SAVE_MEDICATION" + arg0.toString());
						try {
							BaseResult a = new Gson().fromJson(
									arg0.toString(), BaseResult.class);
							if (a == null) {
								return;
							}
							if (a.isFlag()) {
								Toast.makeText(context, "添加成功！",
										Toast.LENGTH_LONG).show();
							} else {
								Toast.makeText(context, a.getMsg() + "",
										Toast.LENGTH_LONG).show();
							}
						} catch (Exception e) {
						}
					}

				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError arg0) {
						disMiss();
						Toast.makeText(context,
								getString(R.string.net_error) + "",
								Toast.LENGTH_LONG).show();
					}
				});

	}

	

	
	@Override
	protected void initData() {

	}

	@Override
	public void onDateSet(DatePickerDialog datePickerDialog, int year,
			int month, int day) {

		if (datePickerDialog == startDatePickerDialog) {
			if (year == 0) {
				startTimeText.setText("");
				return;
			}
			Date d = new Date();
			d.setYear(year - 1900);
			d.setMonth(month);
			d.setDate(day);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(d);
			startTimeText.setText(date);

			startTimePickerDialog.setVibrate(true);
			startTimePickerDialog.setCloseOnSingleTapMinute(true);
			startTimePickerDialog.show(getSupportFragmentManager(),
					TIMEPICKER_TAG);
		} else {
			if (year == 0) {
				endTimeText.setText("");
				return;
			}
			Date d = new Date();
			d.setYear(year - 1900);
			d.setMonth(month);
			d.setDate(day);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(d);
			endTimeText.setText(date);

			endTimePickerDialog.setVibrate(true);
			endTimePickerDialog.setCloseOnSingleTapMinute(true);
			endTimePickerDialog.show(getSupportFragmentManager(),
					TIMEPICKER_TAG);
		}

	}

	@Override
	public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
		if(startTemp==START_CLICK){
			if(hourOfDay==0){
				startTimeText .setText("");
				return;
			}
			String minuteString= minute+"";
			if(minute<10){
				minuteString ="0"+minute;
			}
			String start= startTimeText.getText().toString();
			startTimeText.setText(start+" "+hourOfDay+":"+ minuteString);
			
		}else if(startTemp==END_CLICK){
			
			if(hourOfDay==0){
				endTimeText .setText("");
				return;
			}
			String end= endTimeText.getText().toString();
			
			endTimeText.setText(end+" "+hourOfDay+":"+minute);
		}

	}

	

}

// LinearLayout ll= new LinearLayout(context);
// ll.setOrientation(LinearLayout.VERTICAL);
// ll.setPadding(10, 10,10,10);
// ll.setLayoutParams(parentParams);
//
// LinearLayout nameLayout = new LinearLayout(context);
// nameLayout.setLayoutParams(parentParams);
//
// TextView nameText=new TextView(context);
// nameText.setTextSize(16);
// nameText.setLayoutParams(childParams);
// nameText.setText(R.string.med_name);
//
// EditText nameEdit=new EditText(context);
// nameEdit.setPadding(5, 5,5,5);
// nameEdit.setBackgroundColor(Color.WHITE);
// nameEdit.setLayoutParams(rightParams);
//
// LinearLayout numberLayout = new LinearLayout(context);
//
// numberLayout.setLayoutParams(parentParams);
// parentParams.topMargin=10;
// TextView numberText=new TextView(context);
// numberText.setTextSize(16);
// numberText.setLayoutParams(childParams);
// numberText.setText(R.string.med_number);
//
// EditText numberEdit=new EditText(context);
// numberEdit.setPadding(5, 5,5,5);
// numberEdit.setBackgroundColor(Color.WHITE);
// numberEdit.setLayoutParams(rightParams);
//
// nameLayout.addView(nameText);
// nameLayout.addView(nameEdit);
//
// numberLayout.addView(numberText);
// numberLayout.addView(numberEdit);
//
//
//
// ll.addView(nameLayout);
// ll.addView(numberLayout);




//parentParams= new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.WRAP_CONTENT);
		// childParams= new LayoutParams(LayoutParams.WRAP_CONTENT,
		// LayoutParams.WRAP_CONTENT);
		// rightParams= new LayoutParams(LayoutParams.MATCH_PARENT,
		// LayoutParams.WRAP_CONTENT);
		// rightParams.leftMargin = 10;
